package com.carefree.bookmall.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.carefree.bookmall.exception.CustomException;
import com.carefree.bookmall.service.AliCloudService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @ClassName:AliCloudServiceImpl
 * @Description:
 * @Author Tengbin
 */
@Service(value = "aliCloudService")
public class AliCloudServiceImpl implements AliCloudService {

    private static final String ACCESS_KEY_ID = " ";

    private static final String ACCESS_KEY_SECRET = " ";

    private static final String END_POIND = " ";

    private static final String BUCKET_NAME = " ";

    //OSS的Bucket路径
    private static final String BUCKETPATH = "bookmall/images/";

    /**
     * 上传图片
     *
     * @param multipartFile 文件
     * @return 上传完成后的文件路径
     */
    @Override
    public String uploadImages(MultipartFile multipartFile, String imageType) throws CustomException {

        if (multipartFile.isEmpty()) {
            throw new CustomException("未获取到需上传的图片信息！");
        }

        // oss存储路径
        String returnUrl = "";

        String endpoint = END_POIND;
        String accessKeyId = ACCESS_KEY_ID;
        String accessKeySecret = ACCESS_KEY_SECRET;
        String bucketName = BUCKET_NAME;

        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = multipartFile.getInputStream();
            //获取文件名称
            String fileName = multipartFile.getOriginalFilename();

            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            if ("cover".equals(imageType)) {
                fileName = BUCKETPATH + System.currentTimeMillis() + "_0" + suffixName;
            } else if ("image1".equals(imageType)) {
                fileName = BUCKETPATH + System.currentTimeMillis() + "_1" + suffixName;
            } else if ("image2".equals(imageType)) {
                fileName = BUCKETPATH + System.currentTimeMillis() + "_2" + suffixName;
            } else {
                fileName = BUCKETPATH + System.currentTimeMillis() + suffixName;
            }

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            returnUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnUrl;
    }

    /**
     * 删除已经上传过的图片（用于修改）
     *
     * @param images 需删除的图片文件名集合
     * @return
     */
    @Override
    public boolean deleteUploadedImage(List<String> images) {
        String endpoint = END_POIND;
        String accessKeyId = ACCESS_KEY_ID;
        String accessKeySecret = ACCESS_KEY_SECRET;
        String bucketName = BUCKET_NAME;

        // 创建OSS实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件。
        // 填写需要删除的多个文件完整路径。文件完整路径中不能包含Bucket名称。
        DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(images).withEncodingType("url");

        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);

        // 已删除的文件集合
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();

        if (deletedObjects.isEmpty()) {
            return false;
        }
        return true;
    }
}
